<?php

namespace app\api\controller;
use app\BaseController;
use app\api\model\Backup as BackupModel;
use app\api\exception\ParameterException;
use app\api\service\Media;
use think\helper\Str;

class Backup extends Base {

  public function __construct() {
    $this->model = new BackupModel();
  }

  public function create() {

    $data = input('post.');
    if(isset($data['create_time'])) {
      $data['create_time']= date('Y-m-d H:i:s', strtotime($data['create_time']));
    }

    $bakup_file_name = "./backup.sql";
    $db_host = env('database.hostname');
    $db_name = env('database.database');
    $db_user = env('database.username');
    $db_pass = env('database.password');
    $cmd = config('backup.cmd_path'). " -h {$db_host} -u{$db_user} -p{$db_pass} {$db_name} > {$bakup_file_name} ";
    exec($cmd);

    $path = public_path() . '/public/backup.sql';
    $upload_name = date('YmdHis') . '.sql';
    $media = new Media();
    $result = $media->uploadOss('backup/'.$upload_name, file_get_contents($path));
    
    @unlink($path);

    $data['path'] = $result;

    if(!empty($data['id'])) {
      $this->model->update($data);
    } else {
      $this->model->save($data);
    }
    return success();
  }

  public function delete() {
    $id = input('post.id');
    $result = $this->model->where('id', $id)->field('path')->find();
    $arr = explode('/', $result->path);
    $object = 'cms/backup/' . end($arr);

    $media = new Media();
    $result = $media->deleteOss($object);
   
    $this->model->deleteById($id);
    return success();
  }

}